﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Drawing;
using System.IO;

namespace GpSpotMe.Ign.TileModel
{
    public class IberpixServer
    {
        private static string IBERPIX_URL = "http://ts0.iberpix.ign.es/tileserver/n=mapa_mtn25;z={2};r=4000;i={0};j={1}.jpg";
        
        public static Tile GetTileFromIGN(int i, int j, int z)
        {
            Tile tile;
            WebResponse response = null;
            try
            {

                System.Uri uriIgn = new Uri(string.Format(IBERPIX_URL, i, j,z));
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriIgn.AbsoluteUri);
                request.Timeout = 30000;
                response = request.GetResponse();
                using (Stream str = response.GetResponseStream())
                {
                    Bitmap bmp = new Bitmap(str);
                    tile = new Tile(i, j,z, bmp, true);
                }
            }
            catch (Exception e)
            {
                Bitmap bmp = new Bitmap(256, 256);
                using (Graphics errorGraphics = Graphics.FromImage(bmp))
                {
                    errorGraphics.FillRectangle(new SolidBrush(Color.Coral), 0, 0, bmp.Width, bmp.Height);
                    Brush myBrush = new SolidBrush(Color.Red);
                    Font myFont = new Font(FontFamily.GenericSansSerif, 8, FontStyle.Regular);
                    RectangleF layoutRectangle = new RectangleF(10, 10, 246, 246);
                    errorGraphics.DrawString(e.Message, myFont, myBrush, layoutRectangle);
                }
                tile = new Tile(i, j,z, bmp, false);
            }
            finally
            {
                if (response != null) response.Close();
            }
            return tile;
        }
    }
}
